package com.lanhu.designpattern.singleton.lazy;

/**
 * author:zhangzg
 * date:2020/11/1 1:00
 * 推荐指数5颗星
 */
public class SingletonInnerClass {

    /**
     * 利用静态内部类的加载机制，静态内部类在类加载的时候进行初始化，
     * 但是静态内部类里的静态方法，静态代码块是不会进行初始化的
     * 这样既满足了懒加载的要求，又通过类的加载机制保证了线程安全
     */
    private static class SingletonHolder{
        private static SingletonInnerClass singletonStaticClass = new SingletonInnerClass();
    }

    private SingletonInnerClass(){
        //解决通过反射破坏单例的行为
        if (SingletonHolder.singletonStaticClass != null){
            throw new RuntimeException("SingletonInnerClass already init");
        }
    }

    public static SingletonInnerClass getInstance(){
        return SingletonHolder.singletonStaticClass;
    }

    /**
     * 防止序列化破坏单例
     * @return
     */
    private Object readResolve(){
        return SingletonHolder.singletonStaticClass;
    }


}
